﻿using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using System.Drawing;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using static System.Net.Mime.MediaTypeNames;

namespace ScreenCaputerDemo
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
 

        }
    }
    public static Bitmap CaptureScreen()
    {
        // 创建Direct3D设备
        using (var device = new Device(DriverType.Warp, DeviceCreationFlags.BgraSupport))
        {
            // 获取屏幕的输出适配器
            Adapter adapter = new Factory1().GetAdapter(0);

            // 创建屏幕捕获输出
            using (var output = adapter.GetOutput(0))
            {
                // 获取屏幕的描述信息
                OutputDescription outputDesc = output.Description;

                // 获取屏幕的大小
                int screenWidth = outputDesc.DesktopBounds.Width;
                int screenHeight = outputDesc.DesktopBounds.Height;

                // 创建纹理表面
                Texture2DDescription textureDesc = new Texture2DDescription
                {
                    Format = Format.B8G8R8A8_UNorm,
                    Width = screenWidth,
                    Height = screenHeight,
                    ArraySize = 1,
                    BindFlags = BindFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    MipLevels = 1,
                    Usage = ResourceUsage.Staging,
                    CpuAccessFlags = CpuAccessFlags.Read,
                    OptionFlags = ResourceOptionFlags.None
                };

                using (var screenTexture = new Texture2D(device, textureDesc))
                {
                    // 复制屏幕图像到纹理表面
                    device.ImmediateContext.CopyResource(output.Description.DesktopBounds, screenTexture);

                    // 从设备上下文中读取屏幕图像数据
                    DataStream dataStream;
                    device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out dataStream);

                    // 创建Bitmap对象并复制屏幕图像数据
                    Bitmap bitmap = new Bitmap(screenWidth, screenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, screenWidth, screenHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    dataStream.Position = 0;
                    dataStream.Read((IntPtr)bitmapData.Scan0, screenWidth * screenHeight * 4);
                    bitmap.UnlockBits(bitmapData);

                    // 解除资源映射
                    device.ImmediateContext.UnmapSubresource(screenTexture, 0);

                    return bitmap;
                }
            }
        }
    }
}
